package com.hn658.base.message.notisender.sender.apns;

import java.io.InputStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dbay.apns4j.IApnsService;
import com.dbay.apns4j.impl.ApnsServiceImpl;
import com.dbay.apns4j.model.ApnsConfig;
import com.dbay.apns4j.model.Payload;
import com.hn658.base.message.appinfo.entity.AppInfoEO;
import com.hn658.base.message.appinfo.service.IAppInfoService;
import com.hn658.base.message.common.enums.NotifySenderType;
import com.hn658.base.message.notisender.message.APNSMessage;
import com.hn658.base.message.notisender.sender.AbstractMessageSender;
import com.hn658.framework.file.handlers.IFileHandler;

/**
 * 
 * 苹果消息发送器
 * @author ztjie
 * @date 2015-10-21 下午7:01:43
 * @since
 * @version
 */
@Component("apnsMessageSender")
public class APNSMessageSender extends AbstractMessageSender<APNSMessage> {
    
    // 推送服务对象
    private IApnsService apnsService;
    
    @Autowired(required=false)
    private IFileHandler fileHandler;
    
	@Autowired
	private IAppInfoService appInfoService;
	
	private Lock lock = new ReentrantLock();
	
	private IApnsService getApnsService(String appId){
		if(apnsService==null){
			lock.lock();
			try {
				if(apnsService==null){
					AppInfoEO appInfo = appInfoService.findAppBaiduConfig(appId);
					ApnsConfig apnsConfig = new ApnsConfig();
					InputStream io = fileHandler.readFile(appInfo.getApnsPath());
					apnsConfig.setKeyStore(io);
					apnsConfig.setPassword(appInfo.getApnsPassword());
					apnsConfig.setPoolSize(5);
					apnsService = ApnsServiceImpl.createInstance(apnsConfig);					
				}
			} finally {
				lock.unlock();
			}
		}
		return apnsService;
	}

    @Override
    public void send(APNSMessage message) {
        Payload payload = new Payload();
        payload.setAlert(message.getContent());
        if (null != message.getBadgeCount()) {
            payload.setBadge(message.getBadgeCount());
        }
        payload.setSound("msg.mp3");

        // 256 Bytes is the limit
        while (payload.toString().getBytes().length > 256) {
            StringBuilder alertBuilder = new StringBuilder(payload.getAlert());
            payload.setAlert(alertBuilder.deleteCharAt(alertBuilder.length() - 1).toString());
        }

        this.getApnsService(message.getAppId()).sendNotification(message.getToken().replace(" ",""), payload);
    }
    
    @Override
	public NotifySenderType getTarget() {
		return NotifySenderType.ANPS;
	}
}
